package com.itheima.gatewayadmin.filters;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 后台管理系统，统一鉴权
 */
@Component
@Slf4j
public class AdminAuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求地址
        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse res = exchange.getResponse();
        String requestPath = req.getURI().getPath();
        log.info("请求了: {}", requestPath);
        //2. 白名单过滤（登录请求，放行）
        if (requestPath.startsWith("/admin/login")){
            return chain.filter(exchange);
        }
        //3. 获取请求头的token
        String token = req.getHeaders().getFirst("token");
        //4. 有token
        if (!StringUtils.isEmpty(token)){
            //  4.1 校验token的有效性
            int verifyToken = AppJwtUtil.verifyToken(token);
            if (SystemConstants.JWT_OK == verifyToken){
                //  4.2 有效性放行，return;
                return chain.filter(exchange);
            }
        }
        //否则
        //报401 未认证
        res.setStatusCode(HttpStatus.UNAUTHORIZED);
        return res.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
